package com.wt.admin.service.socket.impl;

import cn.hutool.core.util.ObjectUtil;
import com.wt.admin.config.cache.Cache;
import com.wt.admin.config.socket.WebSocketSessionManager;
import com.wt.admin.domain.dto.socket.SocketMessageDTO;
import com.wt.admin.domain.vo.sys.UserVO;
import com.wt.admin.service.socket.WebSocketEventService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketSession;

import jakarta.annotation.Resource;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class WebSocketEventStrategy implements WebSocketEventService {

    Map<String, WebSocketEventService> eventServiceMap = new ConcurrentHashMap<>();
    @Resource
    Cache<String,UserVO> userCache;

    @Autowired
    public WebSocketEventStrategy(Map<String, WebSocketEventService> eventServiceMap) {
        this.eventServiceMap = eventServiceMap;
    }

    @Override
    public void onConnect(String token, WebSocketSession session) throws IOException {
        // 解析token
        try {
            UserVO uservo = userCache.get(token);
            WebSocketSessionManager.add(uservo, session);
        }catch (Exception e) {
            log.warn("token 进入重新编排 {}", token);
        }
    }

    @Override
    public void onMessage(String token, WebSocketSession session, SocketMessageDTO socketMessageDTO) throws IOException {
        WebSocketEventService webSocketEventService = eventServiceMap.get(socketMessageDTO.getType());
        if(ObjectUtil.isEmpty(webSocketEventService)){
            return;
        }
        webSocketEventService.onMessage(token, session, socketMessageDTO);
    }

    @Override
    public void onClose(String token, WebSocketSession session, CloseStatus closeStatus) throws IOException {
        eventServiceMap.values().stream()
                .forEach(i -> {
                    try {
                        i.onClose(token,session,closeStatus);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                });
        WebSocketSessionManager.remove(token);
    }

}
